<!-- 角色列表页面 -->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 索引列 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            v-for="(item1, index1) in scope.row.children"
            :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                v-for="(item2, index2) in item1.children"
                :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success"
                    closable
                    @close="removeRightById(scope.row, item2.id)">
                    {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    closable
                    @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-tooltip effect="dark" content="编辑" placement="top-start" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除" placement="top-start" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDialog(scope.row.id)">删除</el-button>
            </el-tooltip>
            <!-- 分配权限按钮 -->
            <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <!-- 修改用户角色对话框 -->
    <el-dialog
      title="修改用户角色"
      :visible.sync="modifyDialogVisible"
      width="50%"
      @close="modifyDialogClosed">
      <el-form
      :model="modifyForm"
      :rules="modifyFormRules"
      ref="modifyFormRef"
      label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyUserRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户角色对话框 -->
    <el-dialog
      title="添加用户角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <el-form
      :model="addFormRights"
      :rules="addFormRightsRules"
      ref="addFormRightsRef"
      label-width="90px">
      <el-form-item label="用户角色" prop="roleName">
          <el-input v-model="addFormRights.roleName"></el-input>
        </el-form-item>
        <el-form-item label="用户描述" prop="roleDesc">
          <el-input v-model="addFormRights.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormSure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'Roles',
  components: {},
  data () {
    return {
      // 分页
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      rolesList: [],
      total: 0,
      // 存储修改用户信息
      modifyForm: {},
      // 控制修改权限对话框的显示和隐藏
      modifyDialogVisible: false,
      // 控制添加用户权限的显示和隐藏
      addDialogVisible: false,
      // 修改用户信息的规则
      modifyFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: false,
            message: '请输入用户描述',
            trigger: 'blur'
          }
        ]
      },
      // 存储添加用户权限的信息
      addFormRights: {
        roleName: '',
        roleDesc: ''
      },
      // 存储添加用户权限信息的规则
      addFormRightsRules: {
        roleName: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: false,
            message: '请输入用户描述',
            trigger: 'blur'
          }
        ]
      },
      // 控制分配权限对话框的显示和隐藏
      setRightDialogVisible: false,
      // 存储获取到的所有权限
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      console.log(res)
      this.rolesList = res.data
      this.total = res.data.length
    },
    // 监听页码和当前页
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getRolesList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getRolesList()
    },
    // 编辑按钮
    async editDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户角色失败！')
      }
      this.modifyForm = res.data
      this.modifyDialogVisible = true
    },
    // 点击确认提交修改
    modifyUserRights () {
      this.$refs.modifyFormRef.validate(async valid => {
        if (!valid) return
        // 合法，发起请求
        const { data: res } = await this.$http.put('roles/' + this.modifyForm.roleId, {
          roleName: this.modifyForm.roleName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('提交修改失败！')
        }
        this.modifyDialogVisible = false
        this.getRolesList()
        this.$message.success('提交修改成功！')
      })
    },
    // 监听修改对话框的关闭
    modifyDialogClosed () {
      this.$refs.modifyFormRef.resetFields()
    },
    // 监听添加对话框的关闭
    addDialogClosed () {
      this.$refs.addFormRightsRef.resetFields()
    },
    // 根据ID删除对应的权限,角色数据和权限id
    async removeRightById (role, rightId) {
      // 弹框提示用户是否要删除
      const confirmRes = await this.$confirm('此操作将永久删除该用户权限, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      role.children = res.data
    },
    // 根据用户id删除用户相应的角色
    async removeDialog (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该用户角色, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户角色失败！')
      }
      this.$message.success('删除用户角色成功！')
      // 重新获取用户列表
      this.getRolesList()
    },
    // 点击确认添加角色
    addFormSure () {
      this.$refs.addFormRightsRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户的请求
        const { data: res } = await this.$http.post('roles', this.addFormRights)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getRolesList()
      })
    },
    // 分配权限
    async showSetRightDialog (role) {
      // 获取角色id
      this.roleId = role.id
      // 获取所有权限
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.rightsList = res.data
      console.log(this.rightsList)
      // 递归获取三级节点
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有的三级权限的id，并保存到defKeys数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性，则为三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 控制树形控件的隐藏和清理
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 给角色分配权限
    async allotRights () {
      // 首先需要获取1，2，3级所有被选中的叶子节点和半选中节点并组成一个数组
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      // 形成以，逗号拼接的字符串
      const idStr = keys.join(',')
      // 角色授权
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success('分配权限成功!')
      this.setRightDialogVisible = false
      this.getRolesList()
    }
  },
  computed: {},
  watch: {},
  created () {
    this.getRolesList()
  },
  mounted () {

  }
}
</script>
<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
